//
//  WBNewfeatureView.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/21.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

class WBNewfeatureView: UIView {

    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBAction func enterButtonClick(_ sender: Any) {
        
        removeFromSuperview()
    }
    
    class func newFeatureView() -> WBNewfeatureView{
    
        let nib = UINib(nibName: "WBNewfeatureView", bundle: nil)
        
        let newFeatureView = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewfeatureView
        
        newFeatureView.frame = UIScreen.main.bounds
        
        return newFeatureView
    }
    
    override func awakeFromNib() {
    
        ///1:加载图片
        let count = 4
        
        let rect = UIScreen.main.bounds
        
        
        for i in 0..<count {
            
            let imageName = "new_feature_\(i+1)"
            
            let imageView = UIImageView(image: UIImage(named: imageName))
            
            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(imageView)
        }
        
        /// 设置scrollView的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        
        enterButton.isHidden = true
        
        //设置ScrollView的代理
        scrollView.delegate = self
    }
}


extension WBNewfeatureView: UIScrollViewDelegate{
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        /// 一旦滚动就隐藏按钮
        enterButton.isHidden = true
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        pageControl.currentPage = page
        
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
    
    /// scrollView结束滚动调用的方法
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }
        
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
}
